package View;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;


public class ImagePanel extends JPanel {
    private BufferedImage image;
    
    private int gridWidth = 0;
    private int gridHeight = 0;
    private Color gridColor;
    private boolean gridPainted = false;

    public boolean isGridPainted() {
        return gridPainted;
    }

    public void setGridPainted(boolean gridPainted) {
        this.gridPainted = gridPainted;
        repaint();
    }

    public void setGrid(int w, int h, Color c)
    {
        gridWidth = w;
        gridHeight = h;
        gridColor = c;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            double k = 1;
            int width = image.getWidth();

            if (width > this.getWidth()) {
                k = (double) this.getWidth() / (double) width;
            }

            int height = image.getHeight();
            if (height > this.getHeight()) {
                k = Math.min(k, (double) this.getHeight() / (double) height);
            }

            width *= k;
            height *= k;
            g.drawImage(image, (this.getWidth() - width) / 2, (this.getHeight() - height) / 2, width, height, this);
            
            if (isGridPainted()) {
                int left = (this.getWidth() - width) / 2;
                int right = left + width;
                int top = (this.getHeight() - height) / 2;
                int bottom = top + height;
                float x = left + width / 2;
                while (x < right)
                {
                    g.setColor(gridColor);
                    g.drawLine((int)x, top, (int)x, bottom - 1);
                    x += gridWidth;
                }
                x = left + width / 2;
                while (x > left)
                {
                    g.setColor(gridColor);
                    g.drawLine((int)x, top, (int)x, bottom - 1);
                    x -= gridWidth;
                }
                float y = top + height / 2;
                while (y < bottom)
                {
                    g.setColor(gridColor);
                    g.drawLine(left, (int)y, right - 1, (int)y);
                    y += gridHeight;
                }
                y = top + height / 2;
                while (y > top)
                {
                    g.setColor(gridColor);
                    g.drawLine(left, (int)y, right - 1, (int)y);
                    y -= gridHeight;
                }
            }
        }
    }
}
